<?php

namespace App\Plugin\HostServer\Admin;


use App\Plugin\HostServer\Models\PnHostSvOrder;
use App\Plugin\HostServer\Models\PnHostSvUser;
use Carbon\Carbon;

class OrderController extends BaseController
{
    public $pageName = '订单管理';

    public function setModel()
    {
        $this->model = new PnHostSvOrder();
    }
    public function indexData()
    {
        $status=key_value_arr_to_select(PnHostSvOrder::getStatus());
        array_unshift($status,['id'=>'','name'=>'全部']);
        $data=[
            'status'=>$status
        ];
       return $data;
    }

    public function apiJsonItemExtend($item)
    {
        $item->status_name=PnHostSvOrder::getStatus($item->status);
        return ($item);
    }

    public function createEditData($show = '')
    {
        $status=key_value_arr_to_select(PnHostSvOrder::getStatus());

        return ['status'=>$status];
    }
    //开启事务
    public function beginDb($data, $id = '')
    {
        return 1;
    }

    public function afterSave($model, $id = '')
    {
        //如果是退款
        if($model->status==2)
        {
            //用户退款不存在，才操作，如果存在了，再点击退款无效果
            if(empty($model->refund_at))
            {
                $model->refund_at=date('Y-m-d H:i:s');
                $r=$model->save();
                $user=PnHostSvUser::lockUser($model->user_id);
                return PnHostSvOrder::refund($model,$user) && $r;
            }else
            {
                return 1;
            }

        }else
        {
            return 1;
        }
    }
    public function  show($id)
    {
        $show=$this->model->find($id);
        $data=[
            'show'=>$show
        ];
        return $this->display($data);
    }
    public function checkDelet($id_arr)
    {
        $data=PnHostSvOrder::whereIn('id',$id_arr)->get()->toArray();
        if(empty($data))
        {
            return false;
        }else
        {
            foreach ($data as $k=>$v)
            {
                if($v['status']==1){
                    return '不能允许删除已经支付的订单';
                }
                if($v['ip']){
                    return '不能允许删除已经好的订单';
                }
                if($v['refund_at']){
                    return '不能允许删除已经退款的订单';
                }
            }
        }
    }

}
